﻿using System.Net.Http;
using Kendo.Mvc.UI;
using Kendo.Mvc.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TelerikedIn.Data;
using System.Web.UI.WebControls;
using TelerikedIn.Models;
using TelerikedIn.WebApp.ViewModels.Skills;
using TelerikedIn.WebApp.ViewModels.Endorsments;
using Microsoft.AspNet.Identity;

namespace TelerikedIn.WebApp.Controllers
{
    public class UserSkillsController : Controller
    {
        private UowData data;
        
        public UserSkillsController()
            :this(new UowData())
        {
        }

        public UserSkillsController(UowData data)
        {
            this.data = data;
        }

        //
        // GET: /Skills/
        public ActionResult Index(string userId)
        {
            if (userId == null)
            {
                return PartialView("Error", new HandleErrorInfo(new Exception("User id is null"), "Skills", "Index"));
            }
            ViewData["userId"] = userId;
            return PartialView();
        }

        public ActionResult GetSkillsNotYetAcquired(string userId, string text)
        {
            var skillsNotYetAddedByUser = this.data.Skills.All()
                .Where(s => !s.Users.Any(u => u.Id == userId) && s.Name.Contains(text))
                .Select(SkillVM.FromSkill);
            
            return Json(skillsNotYetAddedByUser, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Read([DataSourceRequest]DataSourceRequest request, string userId)
        {
            if (userId == null)
            {
                throw new HttpRequestException("User was not specified");
            }
            try
            {
                var skills = this.data.Skills.All()
                    .Where(s => s.Users.Any(u => u.Id == userId))
                    .Select(SkillVM.FromSkill).ToList();

                var endorsments = this.data.Endorsments.All()
                    .Where(e => e.ForUserId == userId)
                    .Select(t => t.SkillId).ToList();

                foreach (var skill in skills)
                {
                    skill.EndorsmentsCount = endorsments.Where(e => e == skill.Id).Count();
                }

                return Json(skills.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
            }
            catch
            {
                throw new HttpRequestException("Could not get skills from database!");
            }
        }

        [HttpPost]
        public ActionResult Delete(SkillVM model, string userId)
        {
            try
            {
                var user = this.data.Users.All().FirstOrDefault(u => u.Id == userId);
                if (user != null)
                {
                    user.Skills.Remove(this.data.Skills.GetById(model.Id));
                    this.data.SaveChanges();
                    return Content("");
                }
                else
                {
                    return Content("The skill for this user has been already deleted!");
                }
               
            }
            catch
            {
                return Content("The connection to Database was lost. Try again!");
            }
        }

        [HttpPost]
        [ValidateInput(false)]
        [ValidateAntiForgeryToken]
        public ActionResult AddSkill(string newSkillName, string userId)
        {
            try
            {
                var newSkill = this.data.Skills.All()
                    .FirstOrDefault(sk => sk.Name == newSkillName);
                
                if (newSkill != null &&  newSkill.Users.Any(u => u.Id == userId))
                {
                    return Content("<span class='text-error'>You already have this Skill added.</span>");
                }

                if (newSkill == null)
                {
                    newSkill = new Skill
                    {
                        Name = newSkillName,
                        Users = this.data.Users.All().Where(u => u.Id == userId).ToList()
                    };
                    this.data.Skills.Add(newSkill);

                    this.data.SaveChanges();
                }
                else
                {
                    newSkill.Users.Add(this.data.Users.All().FirstOrDefault(u => u.Id == userId));
                    this.data.SaveChanges();
                }

                return Content("");
            }
            catch
            {
                return Content("<span class='text-error'>This skill is already added!</span>");
            }
        }

        public ActionResult GetEndorsmentDetails(int skillId, 
            [DataSourceRequest]DataSourceRequest request, string userId = null)
        {
            try{
                userId = userId ?? User.Identity.GetUserId();

                var endorsmentsinfo =  this.data.Endorsments.All()
                    .Where(e => e.ForUserId == userId && e.SkillId == skillId)
                    .Select(e => new EndorsmentsMiddleManClassViewModel
                    { 
                        Id = e.Id,
                        ByUserId = e.ByUserId,
                        ByUserName = e.ByUser.FirstName + " " + e.ByUser.LastName,
                        ImageBytes = e.ByUser.Image
                    }).ToList();

                var endorsments = endorsmentsinfo.Select(e => new EndorsmentsVM
                {
                    Id = e.Id,
                    ByUserName = e.ByUserName,
                    ByUserId = e.ByUserId,
                    Image = e.ImageBytes != null && e.ImageBytes.Count() > 8 ?
                            "data:image/png;base64," + Convert.ToBase64String(e.ImageBytes)
                            : "../img/default-image.jpg"
                });

                //foreach (var item in endorsmentsinfo)
                //{
                    //item.Image = 

                //    item.ImageBytes = new byte[1];
                //}

                return Json(endorsments.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
            }
            catch
            {
                return new HttpStatusCodeResult(500, "Data Base Connection lost");
            }
        }
	}
}